// 登录状态管理
const state = {
	userInfo: null,
	isLoggedIn: false,
	token: null
}

const mutations = {
	SET_USER_INFO(state, userInfo) {
		state.userInfo = userInfo
		state.isLoggedIn = !!userInfo
		state.token = userInfo ? userInfo.sessionid : null
	},
	
	CLEAR_USER_INFO(state) {
		state.userInfo = null
		state.isLoggedIn = false
		state.token = null
	}
}

const actions = {
	// 登录
	login({ commit }, userInfo) {
		commit('SET_USER_INFO', userInfo)
		// 保存到本地存储
		uni.setStorageSync('userInfo', userInfo)
	},
	getUserInfo(){
		
	},
	
	// 登出
	logout({ commit }) {
		commit('CLEAR_USER_INFO')
		// 清除本地存储
		uni.removeStorageSync('userInfo')
		uni.removeStorageSync('savedCredentials')
		// 跳转到登录页
		uni.reLaunch({
			url: '/pages/login/login'
		})
	},
	
	// 检查登录状态
	checkLoginStatus({ commit }) {
		const userInfo = uni.getStorageSync('userInfo')
		if (userInfo && userInfo.token) {
			commit('SET_USER_INFO', userInfo)
			return true
		}
		return false
	},
	
	// 初始化应用时检查登录状态
	initAuth({ dispatch }) {
		const isLoggedIn = dispatch('checkLoginStatus')
		return isLoggedIn
	}
}

const getters = {
	userInfo: state => state.userInfo,
	isLoggedIn: state => state.isLoggedIn,
	token: state => state.token,
	username: state => state.userInfo ? state.userInfo.username : ''
}

export default {
	namespaced: true,
	state,
	mutations,
	actions,
	getters
} 